from django.db.models import Q
from django.http import JsonResponse
from rest_framework.views import APIView
from .models import Dept
from .validate import EditValidate, AddValidate
from utils.utils import responseSuccess, responseError, validateError, serializerJSON
from .serializers import LazyListSerializer, TreeSerializer, DetailSerializer

# 系统管理-部门管理-部门表格数据
class LazyListAPI(APIView):
    def get(self,req):
        queryDict = req.query_params.dict()
        if queryDict.get('parentId') == '0':
            # 获取顶级部门
            queryDict['parentId'] = None
        else:
            fields = [field.name for field in Dept._meta.get_fields()]
            # 根据传递条件查询（过滤空值条件，并保留Dept模型中存在的字段）
            queryDict = dict((k,v) for k,v in queryDict.items() if v and k in fields)

        menus = Dept.objects.filter(**queryDict)
        serializers = LazyListSerializer(menus, many=True, context={'exclude': ['children']})
        datas = serializerJSON(serializers)
        return JsonResponse(responseSuccess(datas), safe=False)

# 系统管理-用户管理-左侧的部门树结构
class LazyTreeAPI(APIView):
    def get(self,req):
        parentId = req.query_params.dict().get('parentId')
        q = Q(parentId=None)
        if parentId != '0':
            q = Q(parentId=parentId)
        serializers = TreeSerializer(Dept.objects.only('pk', "deptName","parentId").filter(q), many=True, context={'fields': ['id', 'deptName', 'parentId', 'hasChildren']})
        datas = serializerJSON(serializers)
        return JsonResponse(responseSuccess(datas), safe=False)

# 系统管理-部门管理-新增/编辑弹窗中“上级部门”下拉列表数据
class TreeAPI(APIView):
    def get(self, req):
        serializers = TreeSerializer(Dept.objects.only('pk', 'parentId','deptName').filter(parentId=None), many=True, context={'fields': ['id', 'deptName', 'parentId', 'children']})
        datas = serializerJSON(serializers)
        return JsonResponse(responseSuccess(datas), safe=False)

# 部门详情
class DetailAPI(APIView):
    def get(self, req):
        id = req.query_params.dict().get("id")
        if not id:
            return JsonResponse(responseError('请指定id'), safe=False)
        serializer = DetailSerializer(Dept.objects.get(pk=id), context={'exclude': ['children']})
        return JsonResponse(responseSuccess(serializer.data), safe=False)

# 新增/修改
class SubmitAPI(APIView):
    def post(self,req):
        data = req.data
        edit_id = data.get('id')
        if edit_id:
            obj = Dept.objects.get(id=int(edit_id))
            form = EditValidate(obj, data=data)
        else:
            form = AddValidate(data=data)
        if form.is_valid():
            if edit_id:
                obj = form.update(obj, form.validated_data)
            else:
                obj = form.create(form.validated_data)
            return JsonResponse(responseSuccess(str(obj.pk)), safe=False)
        # 格式化错误信息
        arr = validateError(form.errors)
        return JsonResponse(responseError(arr), safe=False)

class RemoveAPI(APIView):
    def post(self,req):
        ids = req.query_params.dict().get('ids')
        if not ids:
            return JsonResponse(responseError('ids不能为空'), safe=False)
        ids = ids.split(',')
        if not Dept.objects.filter(id__in=ids).exists():
            return JsonResponse(responseError('删除对象不存在'), safe=False)
        result = Dept.objects.filter(id__in=ids).delete()
        if result:
            return JsonResponse(responseSuccess(), safe=False)
        return JsonResponse(responseError('删除失败'), safe=False)
    
